<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    title="查看周转卡"
    width="70%"
    draggable
    @close="closeDialog"
  >
    <!--<div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="生产报工单编号">
          <el-input
            v-model="searchParam.produceReportCode"
            placeholder="请输入生产报工单编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="周转卡编号">
          <el-input
            v-model="searchParam.produceTransferFormCode"
            placeholder="请输入周转卡编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="派工单编号">
          <el-input
            v-model="searchParam.workingFormCode"
            placeholder="请输入派工单编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="工作中心编号">
          <el-input
            v-model="searchParam.workCenterCode"
            placeholder="请输入工作中心编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>-->

    <el-card shadow="never" class="table-container">
      <!--<template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>-->

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        style="height: 450px"
      >
        <el-table-column
          label="周转卡编号"
          prop="turnoverCode"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column
          label="物料编码"
          prop="materialCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="物料名称"
          prop="materialName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="图号"
          prop="figureNumber"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column
          label="条码状态"
          prop="status"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.status === 1">初始打印</span>
            <span v-else>报工关联</span>
          </template>
        </el-table-column>
        <el-table-column
          label="工作中心编号"
          prop="workCenterCode"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="工序"
          prop="processesCode"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.processesName }}
          </template>
        </el-table-column>
        <el-table-column
          label="工序分类"
          prop="processesClassification"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{
              useDictionary(
                "ProcessesClass",
                String(scope.row.processesClassification)
              )
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="数量"
          prop="materialQuantity"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="数量单位"
          prop="quantityUnit"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ useDictionary("MeasurementUnit", scope.row.quantityUnit) }}
          </template>
        </el-table-column>
        <el-table-column
          label="周转卡类型"
          prop="turnoverType"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("TurnoverType", scope.row.turnoverType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="批次号"
          prop="materialBatch"
          min-width="110"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="物料条码"
          prop="materialBarcode"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="更新人"
          prop="lastUpdatedUserName"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="100" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="turnoverCardPrint(scope.row)"
            >
              周转卡补打
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
    <mesproducereportrecord-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!--打印-->
    <div id="printBox" v-if="isPrint" style="opacity: 0">
      <div
        style="margin-bottom: 20px"
        v-for="item in printData"
        :key="item?.id"
      >
        <div
          :id="`printId_${item?.id || ''}`"
          style="width: 384px; height: 394px"
        >
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <!-- <canvas :id="`barcode_${item?.id || ''}`"></canvas> -->
          <div
            style="
              font-size: 12px;
              font-weight: 600;
              word-break: break-all;
              width: 360px;
            "
          >
            <span style="font-size: 18px; font-weight: 100; width: 80%"
              ><text style="font-size: 18px; font-weight: 500">{{
                item?.turnoverCode || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <span style="font-size: 18px; margin-right: 20px; font-weight: 600"
              >产品编号：&nbsp;<text
                style="font-size: 20px; font-weight: 600; margin-right: 20px"
                >{{ item?.materialCode || "" }}</text
              ></span
            >
            <!--            <span
              style="
                font-size: 18px;
                margin-right: 20px;
                font-weight: 600;
              "
              >材质：&nbsp;<text style="font-size: 20px; font-weight: 600">{{
                item?.materialQuality || ""
              }}</text></span
            >-->
          </div>
          <!--          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
                      <br />
                      <span style="font-size: 18px; margin-right: 20px; font-weight: 600"
                        >工作中心：&nbsp;<text
                          style="font-size: 20px; font-weight: 600"
                          >{{ item?.workCenterCode || "" }}</text
                        ></span
                      >
                      <span style="font-size: 18px; margin-right: 20px; font-weight: 600"
                        >类型：&nbsp;<text style="font-size: 20px; font-weight: 600">{{
                          item?.turnoverTypeName || ""
                        }}</text></span
                      >
                    </div>-->
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <br />
            <span style="font-size: 18px; margin-right: 20px; font-weight: 600"
              >图号：&nbsp;<text style="font-size: 20px; font-weight: 600">{{
                item?.figureNumber || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: 0px; width: 390px">
            <br /><span
              style="font-size: 18px; margin-right: 10px; font-weight: 600"
              >生产批次：<text
                style="font-size: 20px; font-weight: 600; margin-right: 10px"
                >{{ item?.materialBatch || "" }}</text
              ></span
            >
            <!--            <span
              style="
                font-size: 18px;
                margin-right: 20px;
                font-weight: 600;
              "
              >数量：&nbsp;<text style="font-size: 20px; font-weight: 600"
                >{{ item?.availableQuantity || "" }}
                {{ item?.quantityUnit || "" }}</text
              >
            </span>-->
          </div>
          <div style="height: 5px"></div>
          <div style="font-size: 12px; width: 390px; margin-bottom: 1px">
            <span style="font-size: 12px; margin-right: 20px; font-weight: 600"
              >打印时间：&nbsp;<text>{{ item?.createTime || "" }}</text></span
            >
            <span
              style="
                font-size: 12px;

                margin-right: 20px;
                font-weight: 600;
              "
              >打印人：&nbsp;<text
                >{{ item?.createdUserName || "" }}&nbsp;</text
              ></span
            >
          </div>
          <div style="height: 5px"></div>
          <div style="font-size: 14px; width: 400px; display: flex">
            <span
              style="
                flex: 1;

                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >操作者1：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
            <span
              style="
                flex: 1;

                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >操作者2：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
            <span
              style="
                flex: 1;

                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >检&nbsp;查：&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
          </div>
          <div
            style="
              font-size: 17px;
              margin-bottom: 0px;
              width: 300px;
              font-weight: 600;
            "
          ></div>
        </div>
        <div style="margin-top: 500px; text-align: center">
          <div style="display: flex; justify-content: center; gap: 10px">
            <!--            <el-button size="small" @click="getPrintData()">打印</el-button>
            <el-button size="small" @click="close()">返回</el-button>-->
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import {
  getDaysByMonth,
  resolveSearchData,
} from "@/views/mes/mescoredemandtotal/utilejs";
import { getLodop } from "@/utils/LocalLodopFuncs";
import { RootObject } from "@/views/demo/iframePrintReturnUnitOne/index";

defineOptions({
  name: "PRODUCEREPORTRECORDPAGE",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesturnovercard/queryCardRecord";

// 是否需要分页
const pagination = true;

const initParam = {};
const emit = defineEmits(["change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  readvisible: {
    type: Number,
    default: () => {
      return null;
    },
  },
});
// 初始化搜索参数数据
const searchParamInit = {
  produceReportCode: "",
  produceTransferFormCode: "",
  workingFormCode: "",
  workingFormId: props.data.id,
  workCenterCode: "",
  processesClassification: props.data.processesClassification,
  planDateId: props.data.planDateId,
};
const visibleDialog = ref(false);
watch(
  () => props.data,
  (newVal: any) => {
    visibleDialog.value = props.visible;
    if (visibleDialog.value) {
      searchParamInit.workingFormId = newVal?.id;
      searchParam.value.workingFormId = newVal?.id;
      searchParamInit.processesClassification = newVal?.processesClassification;
      searchParam.value.processesClassification =
        newVal?.processesClassification;
      searchParamInit.planDateId = newVal?.planDateId;
      searchParam.value.planDateId = newVal?.planDateId;
      getTableList();
    }
  }
);
const deleteParam = {
  api: "/mes/mesproducereportrecord/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行
// async function getTableList(isReset = 0) {
//   // isReset为 1 加载刷新、0 无感知刷新
//   if (isReset === 1) {
//     dataTableRef.value.setScrollTop(0);
//     loading.value = true;
//   }
//   const { data }: any = await request({
//     url: requestApi,
//     method: "post",
//     data: toRaw(searchParamInit),
//   }).catch(() => {});
//   // 数据处理
//   data.forEach((item) => {
//     item.status = String(item.status);
//   });
//   tableData.value = data;
//   loading.value = false;
// }
// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesproducereportrecord/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开生产报工表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改生产报工";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增生产报工";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开生产报工表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "生产报工详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/mesproducereportrecord/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  reset();
}
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
const isPrint = ref(false);

function printNumber(value: any) {
  if (!value) {
    return "请输入数字";
  } else if (isNaN(parseFloat(value)) && isFinite(value)) {
    return "请输入数字";
  } else if (!/^[0-9]+$/.test(value)) {
    return "请输入数字";
  } else if (Number(value) <= 0) {
    return "请输入大于0的值";
  } else {
    return true;
  }
}
//周转卡打印
function turnoverCardPrint(row: any) {
  ElMessageBox.confirm("请确定是否补打?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    isPrint.value = true;
    const res = await request({
      url: `/mes/mesturnovercard/get/${row.id}`,
      method: "get",
    });
    if (res.code == 200) {
      printData.value = [res.data];
      console.log(printData.value);
      setTimeout(() => {
        let LODOP = getLodop();
        LODOP.PRINT_INIT(`周转卡打印-${printData.value[0].turnoverCode}`);
        printData.value?.map((e) => {
          printFun(e, LODOP);
        });
        //LODOP.PRINT(); // 打印
        console.log(LODOP.Printers.list);
        LODOP.PREVIEW(); // 预览
        isPrint.value = false;
        window.parent.postMessage("打印中，请稍后...", "*");
      }, 1000);
    }
  });
  // ElMessageBox.prompt(`请输入打印次数`, "打印", {
  //   confirmButtonText: "确定",
  //   cancelButtonText: "取消",
  //   dangerouslyUseHTMLString: true,
  //   inputValidator: (value: string) => printNumber(value),
  //   beforeClose: (action, instance, done) => {
  //     if (action === "confirm") {
  //       // 开启按钮加载
  //       instance.confirmButtonLoading = true;
  //       isPrint.value = true;
  //       row.counts = instance.inputValue;
  //       getPrintData(row);
  //       done();
  //     } else {
  //       done();
  //     }
  //   },
  // }).catch(() => {});
}
// 打印数据，数组形式
const printData = ref<any[]>([]);
async function getPrintData(row: any) {
  const { data } = await request({
    url: `/mes/mesturnovercard/prints`,
    method: "post",
    data: { counts: row.counts, mesPlanWorkingForm: row },
  }).finally(() => {});
  printData.value = data;
  setTimeout(() => {
    let LODOP = getLodop();
    LODOP.PRINT_INIT(`周转卡打印-${printData.value[0].turnoverCode}`);
    printData.value?.map((e) => {
      printFun(e, LODOP);
    });
    //LODOP.PRINT(); // 打印
    console.log(LODOP.Printers.list);
    LODOP.PREVIEW(); // 预览
    isPrint.value = false;
    window.parent.postMessage("打印中，请稍后...", "*");
  }, 1000);
}

function printFun(pitem: any, LODOP: any) {
  LODOP.SET_PRINT_PAGESIZE(1, "100mm", "100mm", ""); // 设置纸张类型（方向、宽度、高度、纸张类型名称）
  LODOP.ADD_PRINT_HTM(
    "38mm",
    "3mm",
    "100mm",
    "100mm",
    document.getElementById(`printId_${pitem?.id || ""}`)?.innerHTML
  );
  LODOP.ADD_PRINT_BARCODE(
    "5mm",
    "30mm",
    "40mm",
    "40mm",
    "QRCode",
    pitem?.turnoverCode || ""
  );
  LODOP.NEWPAGE(); //另起一页
}
</script>
